import React from 'react';
import { Card, Form, Input, Button, Space, Table, Tag, Modal, Steps, message } from 'antd';

const payTypeList = [
  { value: '1', label: '微信' },
  { value: '2', label: '支付宝' },
  { value: '3', label: '现金' },
  { value: '5', label: '会员卡' },
];

const rentStateList = [
  { value: 0, label: '待处理' },
  { value: 1, label: '处理中' },
  { value: 2, label: '已完成' },
  { value: 5, label: '已取消' },
];

function getDictLabel(list, value) {
  const item = list.find((i) => String(i.value) === String(value));
  return item ? item.label : value;
}

// 模拟充值记录数据
const mockRecharge = [
  { id: 1, userName: '王五', orderNumber: 'RN202510110001', payAccount: 'wx_zhangsan', price: 100, state: 1, payType: '1', createTime: '2025-10-11 13:20:00' },
  { id: 2, userName: '赵六', orderNumber: 'RN202510100002', payAccount: 'ali_lisi', price: 50.5, state: 2, payType: '2', createTime: '2025-10-10 10:02:10' },
  { id: 3, userName: 'Tom', orderNumber: 'RN202510090003', payAccount: 'card_8888', price: 120, state: 0, payType: '5', createTime: '2025-10-09 08:33:21' },
];

export default function RechargeRecord() {
  const [form] = Form.useForm();
  const [loading, setLoading] = React.useState(false);
  const [page, setPage] = React.useState({ pageSize: 10, pageIndex: 1, totalSize: mockRecharge.length });
  const [search, setSearch] = React.useState({ orderNumber: '', userName: '' });
  const [allList] = React.useState(mockRecharge);
  const [renewalRecordList, setRenewalRecordList] = React.useState([]);

  // 弹窗相关
  const [dialogRecharge, setDialogRecharge] = React.useState(false);
  const [dialogRenew, setDialogRenew] = React.useState(false);
  const [activeStep, setActiveStep] = React.useState(0);
  const [processStatus, setProcessStatus] = React.useState('process');
  const [currentRecord, setCurrentRecord] = React.useState(null);

  React.useEffect(() => {
    form.setFieldsValue({ orderNumber: '', userName: '' });
    applySearch(1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function applySearch(newPageIndex = page.pageIndex, newPageSize = page.pageSize, nextSearch = search) {
    setLoading(true);
    const filtered = allList.filter((r) => (
      (!nextSearch.orderNumber || String(r.orderNumber).includes(nextSearch.orderNumber)) &&
      (!nextSearch.userName || String(r.userName).includes(nextSearch.userName))
    ));
    const start = (newPageIndex - 1) * newPageSize;
    const end = start + newPageSize;
    setRenewalRecordList(filtered.slice(start, end));
    setPage({ pageIndex: newPageIndex, pageSize: newPageSize, totalSize: filtered.length });
    setLoading(false);
  }

  function onSubmit(values) {
    const next = { ...search, ...values };
    setSearch(next);
    applySearch(1, page.pageSize, next);
  }

  function resetSearch() {
    const next = { orderNumber: '', userName: '' };
    form.setFieldsValue(next);
    setSearch(next);
    applySearch(1, page.pageSize, next);
  }

  function onTableChange(pagination) {
    const newPageIndex = pagination.current || 1;
    const newPageSize = pagination.pageSize || page.pageSize;
    applySearch(newPageIndex, newPageSize);
  }

  // 操作
  function nextStep(row) {
    setCurrentRecord(row);
    setActiveStep(Math.min(parseInt(row.state, 10) + 1, 2));
    setProcessStatus(parseInt(row.state, 10) >= 2 ? 'finish' : 'process');
    setDialogRecharge(true);
  }

  function revoke(row) {
    message.success('已发起撤销（示例）');
  }

  function renew(row) {
    setCurrentRecord(row);
    setDialogRenew(true);
  }

  function closeRecharge(stateChanged) {
    setDialogRecharge(false);
    if (stateChanged) applySearch(page.pageIndex, page.pageSize, search);
  }

  function closeRenew(stateChanged) {
    setDialogRenew(false);
    if (stateChanged) applySearch(page.pageIndex, page.pageSize, search);
  }

  const columns = [
    { dataIndex: 'userName', title: '用户名', align: 'center', width: 200 },
    { dataIndex: 'orderNumber', title: '订单号', align: 'center', width: 170 },
    { dataIndex: 'payAccount', title: '充值账号', align: 'center', width: 170 },
    { dataIndex: 'price', title: '金额', align: 'center', width: 140, render: (v) => v ? `$${parseFloat(v).toFixed(2)}` : '' },
    { dataIndex: 'state', title: '状态', align: 'center', render: (v) => <Tag>{getDictLabel(rentStateList, v)}</Tag> },
    { dataIndex: 'payType', title: '支付方式', align: 'center', render: (v) => getDictLabel(payTypeList, v) },
    { dataIndex: 'createTime', title: '创建时间', align: 'center' },
    {
      fixed: 'right',
      title: '操作',
      align: 'center',
      width: 220,
      render: (_, row) => (
        <Space>
          {row.state !== 5 ? (
            <>
              <Button type="primary" size="small" onClick={() => nextStep(row)}>详情</Button>
              {row.state === 0 && (
                <Button danger size="small" onClick={() => revoke(row)}>撤销</Button>
              )}
              {row.state === 1 && (
                <Button type="default" size="small" onClick={() => renew(row)}>续费</Button>
              )}
            </>
          ) : (
            <Tag>已取消</Tag>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="renewal-record">
      {/* 查询区域 */}
      <Card style={{ marginBottom: 12 }}>
        <Form form={form} layout="inline" onFinish={onSubmit}>
          <Form.Item name="orderNumber" label="订单号">
            <Input placeholder="输入订单号" allowClear />
          </Form.Item>
          <Form.Item name="userName" label="用户名">
            <Input placeholder="输入用户名" allowClear />
          </Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">查询</Button>
            <Button onClick={resetSearch}>重置</Button>
          </Space>
        </Form>
      </Card>

      {/* 列表区域 */}
      <Card className="vue-padding radius">
        <Table
          rowKey="id"
          loading={loading}
          dataSource={renewalRecordList}
          columns={columns}
          bordered
          scroll={{ y: 638 }}
          pagination={{
            current: page.pageIndex,
            pageSize: page.pageSize,
            total: page.totalSize,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
          onChange={onTableChange}
          locale={{ emptyText: '暂无数据' }}
          style={{ width: '100%' }}
        />
      </Card>

      {/* 充值详情弹窗（步骤演示） */}
      <Modal title="充值详情" open={dialogRecharge} onCancel={() => closeRecharge(false)} onOk={() => closeRecharge(true)} width={600}>
        <Steps current={activeStep} status={processStatus} items={[
          { title: '提交申请' },
          { title: '渠道扣款' },
          { title: '充值完成' },
        ]} />
        <div style={{ marginTop: 16 }}>
          {currentRecord && (
            <div style={{ lineHeight: 2 }}>
              <div>订单号：{currentRecord.orderNumber}</div>
              <div>充值账号：{currentRecord.payAccount}</div>
              <div>金额：${parseFloat(currentRecord.price).toFixed(2)}</div>
            </div>
          )}
        </div>
      </Modal>

      {/* 续费确认弹窗 */}
      <Modal title="确认续费" open={dialogRenew} onCancel={() => closeRenew(false)} onOk={() => { message.success('续费成功（示例）'); closeRenew(true); }} width={420}>
        <div>确认对所选记录发起续费？</div>
      </Modal>
    </div>
  );
}